package com.dean.service;

import java.time.LocalDateTime;
import java.util.concurrent.*;

import com.dean.entity.DeanExportInfo;
import com.dean.entity.DeanImportInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * 线程池初始化
 * @author Administrator
 *
 */
public class DeanExecutorService {
	
	private static final Logger logger = LoggerFactory.getLogger(DeanExecutorService.class);

	/**
	 * 截至目前已产生的任务总数
	 */
	private static volatile long totalProducrTask = 0;
	/**
	 * 截至目前已消费的任务总数
	 */
	private static volatile long totalConsumerTask = 0;

	private static ThreadPoolExecutor executorService =
			new ThreadPoolExecutor(4,8,30, TimeUnit.SECONDS,
					new ArrayBlockingQueue<>(16),
					Executors.defaultThreadFactory(),
					new ThreadPoolExecutor.AbortPolicy());
	
	private DeanExecutorService() {}
	
	public static ThreadPoolExecutor getInstance() {
		return executorService;
	}
	public synchronized static void producer(String taskName){
		++totalProducrTask;
		logger.info("追加任务{},追加任务时间{},当前剩余任务总量为:{}",taskName,LocalDateTime.now(),totalProducrTask-totalConsumerTask);
	}
	public synchronized static void consumer(String taskName){
		++totalConsumerTask;
		logger.info("已完成任务{},任务完成时间{},当前剩余任务总量为:{}",taskName,LocalDateTime.now(), totalProducrTask-totalConsumerTask);
		if(totalProducrTask == totalConsumerTask){
			logger.info("截至目前,所有任务已执行完成，完成时间:{}",LocalDateTime.now());
		}
	}

	public synchronized static void count(){
		logger.info("截至目前已累计追加任务数为{},累计已完成的任务数为{}",totalProducrTask,totalConsumerTask);
	}

	public static void exeFileImp(DataFileImpExpService service, DeanImportInfo importInfo){
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				producer(importInfo.toString());
				service.imp(importInfo);
				consumer(importInfo.toString());
			}
		};
		getInstance().execute(runnable);

	}

	public static void exeFileExp(DataFileImpExpService service, DeanExportInfo exportInfo){
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				producer(exportInfo.toString());
				service.exp(exportInfo);
				consumer(exportInfo.toString());
			}
		};
		getInstance().execute(runnable);
	}
}
